package com.zzxx.exam.service;

import com.zzxx.exam.entity.EntityContext;
import com.zzxx.exam.entity.ExamInfo;
import com.zzxx.exam.entity.QuestionInfo;
import com.zzxx.exam.entity.User;
import com.zzxx.exam.ui.FrameManager;

import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/** 软件的核心功能：登陆，开始(发卷)，交卷... */
public class Controller {

    /**
     * login()
     *
     * createPaper()
     *
     * 上一题
     *
     * 下一题
     *
     * 交卷
     *
     * 计算分数
     *
     */

    //各个模块层
    EntityContext entityContext = new EntityContext();
    FrameManager frameManager = new FrameManager(this);

    //当前用户
    private User nowUser;

    //当前题目
    private QuestionInfo nowQuestionInfo;

    //试卷
    ArrayList<QuestionInfo> testPaper = new ArrayList<>();

    //考试信息
    ExamInfo nowExamInfo;

    //刷新线程
    Thread timerRunner;
    //提前交卷标签
    private boolean submitEarly = false; //默认不提前
    //时间刷新任务
    Runnable run = new Runnable() {
        @Override
        public void run() {
            //版本三，直接数运算 ,默认传过来的时间是分钟为单位
            long deadline = nowExamInfo.getTimeLimit() * 60L; //化成秒
            while (deadline >= 0){
                if (submitEarly)break;
                try {
                    Thread.sleep(1000L);  //数大一点，减少误差
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //传递时间信息
                String hour = String.valueOf(deadline / 60L / 60L);
                String min = String.valueOf(deadline % (60L * 60) / 60L);
                String sec = String.valueOf(deadline % 60L);
                frameManager.refreshExamTime(hour, min, sec);
                deadline--;
            }
            if (!submitEarly) {
                //时间结束,自动交卷
                JOptionPane.showConfirmDialog(null, "时间到，已自动交卷", "警告", JOptionPane.DEFAULT_OPTION);
                submit();
            }
        }
    };

    //闪屏等待时间
    public static final long WAITE_TIME = 1000L;

    //考试记录
    private StringBuilder history = new StringBuilder("日期                  - 分数");

    public Controller(){
    }

    //程序开始
    public void startSystem(){
        frameManager.startSystem();
    }


    //登录
    public void login(String id, String password){
        String tips = "";
        if (id.equals("")/* || id == null*/) {
            //没写账号
            tips = "账号不能为空";
        } else {
            int idIn = Integer.parseInt(id);
            User user = entityContext.getUserById(idIn);
//                User user = new User("dwdwd",123, "1234");
            if (user == null) {
                //用户不存在
                tips = "用户不存在";
            } else {
                if (user.getPassword().equals(password)) {
                    //登录成功
                    nowUser = user;
                    frameManager.showMenu();
                } else {
                    //密码错误
                    tips = "密码错误";
                }
            }
        }
        frameManager.getMessagePanel().setText(tips);
    }

    //发卷（生成试卷)
    public void creatPaper(){
        testPaper = entityContext.getTestPaper();
        nowQuestionInfo = testPaper.get(0);
    }

    //上一题
    public void prev(){
        //判断是否为第一题
        if (nowQuestionInfo.getQuestionIndex() == 1){
            JOptionPane.showConfirmDialog(null, "这就是第一题，别点了", "提示", JOptionPane.DEFAULT_OPTION);
        }else {
            //记录当前题答案并把当前题变量改成上一题
            testPaper.set(nowQuestionInfo.getQuestionIndex() - 1, nowQuestionInfo);
            nowQuestionInfo = testPaper.get(nowQuestionInfo.getQuestionIndex() - 2);
            frameManager.refreshExamFace();

            //测试
//            nowQuestionInfo = testPaper.get(nowQuestionInfo.getQuestionIndex() - 2);
//            System.out.println("" + nowQuestionInfo.getQuestionIndex() + "  " + nowQuestionInfo.getQuestion());

        }
    }

    //下一题
    public void next(){
        //判断是否为最后一题
        if (nowQuestionInfo.getQuestionIndex() == 20){
            int i = JOptionPane.showConfirmDialog(null, "已是最后一题了，确认交卷？", "提示", JOptionPane.YES_NO_OPTION);
            if (i == JOptionPane.YES_OPTION){
                //交卷
                submit();
            }
        }else { // 不是最后一题
            //记录当前题答案并把当前题变量改成下一题
            //从界面拿到当前题的信息
            nowQuestionInfo = frameManager.getNowQuestionInfo();

            //移动到下一题，并赋值到试卷内
            testPaper.set(nowQuestionInfo.getQuestionIndex() - 1, nowQuestionInfo); //下标比题号小1
            nowQuestionInfo = testPaper.get(nowQuestionInfo.getQuestionIndex());
            frameManager.refreshExamFace();

            //测试用
//            nowQuestionInfo = testPaper.get(nowQuestionInfo.getQuestionIndex());
//            System.out.println("" + nowQuestionInfo.getQuestionIndex() + "  " + nowQuestionInfo.getQuestion());
        }
    }

    //交卷,并关闭时间
    public void submit(){
        //结束时间器
//        timerRunner.stop();

        //最后一题的bug （可能未保存用户答案）
        nowQuestionInfo = frameManager.getNowQuestionInfo();
        //移动到下一题，并赋值到试卷内
        testPaper.set(nowQuestionInfo.getQuestionIndex() - 1, nowQuestionInfo); //下标比题号小1

        //检查分数并展示
        int totalScore = countScore();
        //记录历史
        history.append("\n" + new SimpleDateFormat("MM-dd-HH:mm").format(new Date()) + "       -  " + totalScore);

        JOptionPane.showConfirmDialog(null, "总分为：" + totalScore, "考试结果", JOptionPane.DEFAULT_OPTION);
        frameManager.overExam();
    }

    //计算分数
    public int countScore(){
        int sum = 0;
        //题目还未设置分数
        //判断相互包含,多选要全对，不然不给分
        for (int i = 0; i < testPaper.size(); i++) {
            if (testPaper.get(i).getUserAnswers().containsAll(testPaper.get(i).getQuestion().getAnswers())
                && testPaper.get(i).getQuestion().getAnswers().containsAll(testPaper.get(i).getUserAnswers())){
                //都包含，正确
                sum += testPaper.get(i).getQuestion().getScore();
            }
        }
        return sum;
    }

    //开始考试
    public void startExam() {
        creatPaper();  //创建试卷
        //获取考试信息
        initExamInfo();
        //让提前交卷变false
        submitEarly = false;

        startTime();
        frameManager.initFace();
        frameManager.showExam();
    }

    private void initExamInfo() {
        nowExamInfo = entityContext.getExamInfo();
        nowExamInfo.setUser(nowUser);
    }

    //获取规则
    public String getRule() {
        return entityContext.giveRule();
    }



    public String getUserName() {
        return nowUser.getName();
    }

    public QuestionInfo getNowQuestionInfo() {
        return nowQuestionInfo;
    }

    public void startTime() {
        //搞一条线程让考试界面一直刷新,记得关
        timerRunner = new Thread(run);  //新建，避免多次开启
        timerRunner.start();
    }

    //获取历史记录
    public String getHistory() {
        return String.valueOf(history);
    }

    public ExamInfo getNowExamInfo() {
        return nowExamInfo;
    }

    public void setSubmitEarly() {
        submitEarly = true;
    }
}
